<?php

namespace app\admin\controller\store;

use app\api\model\GoodsProduct;
use app\api\model\GoodsSpecification;
use app\common\controller\Backend;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
    protected $noNeedRight = '*';
    /**
     * Goods模型对象
     * @var \app\admin\model\store\Goods
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\store\Goods;
        $this->view->assign("isHotList", $this->model->getIsHotList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("isSevenDaysList", $this->model->getIsSevenDaysList());
        $this->view->assign("goodsTypeList", $this->model->getGoodsTypeList());
        $this->view->assign("isOnSaleList", $this->model->getIsOnSaleList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'name', 'join_merchant_id', 'gallery_images', 'is_on_sale', 'goods_image', 'guarantee', 'sort_order', 'unit', 'counter_price', 'retail_price', 'details_content']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function sku()
    {
        return $this->view->fetch('', [
            'id' => input('id')
        ]);
    }

    public function save_sku()
    {
        $params = input();
        if ($params['type'] && $params['type'] == '1'){
            $validate = $this->validate($params, [
                'type'              => 'require',
                'goods_id'          => 'require',
                'specifications'    => 'require',
                'value'             => 'require',
                'price'             => 'require',
                'number'            => 'require'
            ]);
            if ($validate !== true) {
                return json([
                    'code' => -1,
                    'msg' => $validate
                ]);
            }
        }

        Db::startTrans();

        try {
            $goodsProduct = GoodsProduct::getByStoreGoodsId($params['goods_id']);
            if (!empty($goodsProduct)){
                $goods = \app\admin\model\store\Goods::getById($params['goods_id']);
                if (!empty($goods)){
                    GoodsProduct::where('store_goods_id',$params['goods_id'])->delete();
                    GoodsSpecification::where('store_goods_id',$params['goods_id'])->delete();

                }
            }
            // 如果为空，则添加
            if ($params['type'] == '1') {
                GoodsProduct::create([
                    'store_goods_id'        => $params['goods_id'],
                    'specifications'        => explode(',', $params['specifications']),
                    'price'                 => $params['price'],
                    'number'                => $params['number'],
                    'createtime'            => time(),
                    'updatetime'            => time()
                ]);
                GoodsSpecification::create([
                    'store_goods_id'        => $params['goods_id'],
                    'specification'         => $params['specifications'],
                    'value'                 => $params['value'],
                    'createtime'            => time(),
                    'updatetime'            => time()
                ]);
            }else{
                foreach ($params['specList'] as $spec){
                    foreach ($spec['attr'] as $value){
                        GoodsSpecification::create([
                            'store_goods_id'       =>  $params['goods_id'],
                            'specification'        =>  $spec['label'],
                            'value'                =>  $value
                        ]);
                    }
                }

                foreach ($params['specData'] as $data){
                    GoodsProduct::create([
                        'store_goods_id'        => $params['goods_id'],
                        'specifications'        => $data['spec'],
                        'price'                 => $data['price'],
                        'number'                => $data['stock'],
                        'url'                   => $data['img'],
                        'createtime'            => time(),
                        'updatetime'            => time()
                    ]);
                }
            }

            \app\admin\model\store\Goods::update([
                'type' => $params['type'],
            ], ['id' => $params['goods_id']]);


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json([
                'code' => -1,
                'msg' => '添加失败' . $e->getMessage()
            ]);
        }
        return json([
            'code' => 1,
            'msg' => '保存成功'
        ]);
    }
    public function goodsDetail()
    {
        $id = input('goods_id');
        if (empty($id)){
            return json([
                'code' => -1,
                'msg' => '请选择商品'
            ]);
        }
        $goods = \app\admin\model\store\Goods::getById($id);
        if (empty($goods)){
            return json([
                'code' => -1,
                'msg' => '商品不存在'
            ]);
        }

        if ($goods['type'] == '1'){
            $goodsSpec      = GoodsSpecification::getByStoreGoodsId($id);
            $goodsProduct   = GoodsProduct::getByStoreGoodsId($id);
            return json([
                'code'  => 1,
                'msg'   => '成功',
                'type'  => $goods['type'],
                'data'  =>  [
                    'specifications'  => $goodsSpec['specification'],
                    'value'           => $goodsSpec['value'],
                    'price'           => $goodsProduct['price'],
                    'number'          => $goodsProduct['number'],
                ]
            ]);
        }else{
            $goodsList = [];
            $goodsData = [];
            $goodsSpec = GoodsSpecification::where('store_goods_id',$id)
                ->group('specification')
                ->select();
            if (!empty($goodsSpec)){
                foreach ($goodsSpec as $value){
                    $goodsList[$value['specification']]['label'] = $value['specification'];
                    $goodsList[$value['specification']]['attr']  = [$value['value']];
                }
            }
            $goodsProduct = GoodsProduct::where('store_goods_id',$id)->select();
            if (!empty($goodsProduct)){
                foreach ($goodsProduct as $value){
                    $goodsData[] = [
                        'spec'   => $value['specifications'],
                        'price'  => $value['price'],
                        'stock'  => $value['number']
                    ];
                }
            }
            return json([
                'code'  => 1,
                'msg'   => '成功',
                'type'  => $goods['type'],
                'data'  =>  [
                    'specList'  => array_values($goodsList),
                    'specData'  => $goodsData
                ]
            ]);
        }

    }
}
